<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="orderList">
      <el-table-column
        label="序号"
        align="center"
        prop="id"
        type="index"
        width="55px"
      />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column
        label="商品名称"
        align="center"
        prop="skuName"
        width="130px"
      />
      <el-table-column
        label="订单金额"
        align="center"
        prop="amount"
        width="130px"
      />
      <el-table-column
        label="设备编号"
        align="center"
        prop="innerCode"
        width="130px"
      />
      <el-table-column
        label="订单状态"
        align="center"
        prop="status"
        width="130px"
      >
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="createTime">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="getOrderInfo(scope.row)"
            v-hasPermi="['manage:order:query']"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 查看详情对话框 -->
    <el-dialog title="订单详情" v-model="open" width="520px" append-to-body>
      <el-descriptions :column="1" border style="width: 100%">
        <el-descriptions-item label="订单编号">{{
          orderInfo.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{
          orderInfo.skuName
        }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">{{
          orderInfo.amount
        }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="order_status" :value="orderInfo.status" />
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <dict-tag :options="pay_status" :value="orderInfo.payStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="设备编号">{{
          orderInfo.innerCode
        }}</el-descriptions-item>
        <el-descriptions-item label="设备地址">{{
          orderInfo.addr
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ parseTime(orderInfo.createTime, "{y}-{m}-{d} {h}:{m}:{s}") }}
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">
          {{ parseTime(orderInfo.updateTime, "{y}-{m}-{d} {h}:{m}:{s}") }}
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">{{
          orderInfo.payType == "wxpay"
            ? "微信支付"
            : orderInfo.payType == "alipay"
            ? "支付宝支付"
            : "未支付"
        }}</el-descriptions-item>
        <el-descriptions-item label="交易单号" v-if="orderInfo.thirdNo">{{
          orderInfo.thirdNo
        }}</el-descriptions-item>
        <el-descriptions-item label="取消原因" v-if="orderInfo.cancelDesc">{{
          orderInfo.cancelDesc
        }}</el-descriptions-item>
      </el-descriptions>
      <el-row style="margin-top: 20px">
        <el-col
          :span="24"
          style="text-align: right"
          v-if="
            (orderInfo.status == 3 && orderInfo.payStatus in [1, 2]) || //出货失败且支付完成
            (orderInfo.payStatus == 2 && orderInfo.status == 1) //退款中且支付完成
          "
        >
          <el-button type="danger" @click="handleRefund(orderInfo)"
            >退款</el-button
          >
        </el-col>
        <el-col
          :span="24"
          style="text-align: right"
          v-if="orderInfo.status == 0"
        >
          <el-button type="danger" @click="handleCloseOrder(orderInfo)"
            >关闭订单</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  getOrderByOrderNo,
} from "@/api/manage/order";

const { proxy } = getCurrentInstance();
const { pay_status, order_status } = proxy.useDict(
  "pay_status",
  "order_status"
);

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    channelCode: null,
    status: null,
    payStatus: null,
    regionId: null,
    partnerId: null,
    nodeId: null,
  },
  rules: {
    orderNo: [{ required: true, message: "订单编号不能为空", trigger: "blur" }],
    amount: [{ required: true, message: "支付金额不能为空", trigger: "blur" }],
    price: [{ required: true, message: "商品金额不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/**关闭订单按钮 */
function handleCloseOrder(row) {
  proxy
    .$confirm("是否确认关闭订单?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(function () {
      return updateOrder({
        orderNo: row.orderNo,
        status: 4,
      });
    })
    .then(() => {
      proxy.$modal.msgSuccess("关闭成功");
      open.value = false;
      getList();
    });
}

/**退款按钮 */
function handleRefund(row) {
  proxy
    .$confirm("是否确认退款?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(function () {
      return updateOrder({
        orderNo: row.orderNo,
        payStatus: 3,
      });
    })
    .then(() => {
      proxy.$modal.msgSuccess("退款成功");
      open.value = false;
    });
}

/**查看详情按钮 */
const orderInfo = ref({});
function getOrderInfo(row) {
  reset();
  orderInfo.value = {};
  getOrderByOrderNo(row.orderNo).then((response) => {
    orderInfo.value = response.data;
    open.value = true;
  });
}

/**选择日期按钮 */
const dateRange = ref([]);
/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.startDate = dateRange.value[0];
  queryParams.value.endDate = dateRange.value[1];
  listOrder(queryParams.value).then((response) => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    thirdNo: null,
    innerCode: null,
    channelCode: null,
    skuId: null,
    skuName: null,
    classId: null,
    status: null,
    amount: null,
    price: null,
    payType: null,
    payStatus: null,
    bill: null,
    addr: null,
    regionId: null,
    regionName: null,
    businessType: null,
    partnerId: null,
    openId: null,
    nodeId: null,
    nodeName: null,
    cancelDesc: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getOrder(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delOrder(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/order/export",
    {
      ...queryParams.value,
    },
    `order_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
